package com.ljx.springcloud.controller;

import com.ljx.springcloud.entities.Dept;
import com.ljx.springcloud.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class DeptController {

    @Autowired
    private DeptService service;

    @Autowired
    private DiscoveryClient client;

    @RequestMapping(value = "/dept/all",method = RequestMethod.GET)
    @ResponseBody
    public List<Dept> findall(){
        return service.findAll();
    }

    @RequestMapping(value = "/dept/add",method = RequestMethod.POST)
    @ResponseBody
    public String add(@RequestParam("dept") Dept dept){
        return String.valueOf(service.addDept(dept));
    }

    @RequestMapping(value = "/dept/get/{id}",method = RequestMethod.GET)
    @ResponseBody
    @HystrixCommand(fallbackMethod = "fallbcak_get")
    public Dept get(@PathVariable("id") String id){
        Dept dept = service.findById(Long.valueOf(id));
        if (dept == null){
            throw new NullPointerException();
        }
        return dept;
    }


    public Dept fallbcak_get(@PathVariable("id") String id){
        return new Dept().setDname("name is null use HystrixCommand").setDeptno(Long.valueOf(id)).setDb_source("no data in db");
    }

    @RequestMapping(value = "/eureka/get/",method = RequestMethod.GET)
    @ResponseBody
    public Object getEureka(){
        List<String> serviceInstances = client.getServices();
        System.out.println(serviceInstances);
        List<ServiceInstance> serviceInstances1 = client.getInstances("microservicecloud-provider-dept");
        for (ServiceInstance s : serviceInstances1) {
            System.out.println(s.getHost()+","+s.getUri()+","+s.getPort());
        }
        return client;
    }
}
